<template>
  <div id="promotionPage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <!-- 表格篩選 -->
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-button type="primary" @click="handleCreate">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <!-- <template #title>
          <a-alert message="優先順序數字越大執行優先級越高"  show-icon  />
        </template> -->
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
          <template v-if="column.dataIndex === 'priority'">
            <a-tooltip>
              <template #title>優先順序數字越大,執行優先級越高</template>
              <a-typography-text strong type="danger">優先級</a-typography-text>
              <QuestionCircleOutlined />
            </a-tooltip>
          </template>
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'type'">
            <template v-if="record.type === 1">AIA醫療計劃</template>
            <template v-else-if="record.type === 2">定額優惠券</template>
            <template v-else-if="record.type === 3">折扣卡</template>
            <template v-else>全部</template>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag
              :bordered="false"
              color="processing"
              v-if="record.status == 1"
              >啟用</a-tag
            >
            <a-tag :bordered="false" v-else>禁用</a-tag>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleView(record)">查看</a-button>
            <a-button @click="handleEdit(record)">修改</a-button>
            <a-button danger @click="handleDelete(record)">刪除</a-button>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 新建模態框 -->
    <a-modal v-model:open="showModalCreate" title="新建推廣計劃" :footer="null">
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯推廣計劃
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { promotionApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  filterFields,
  getCreateFieldConfig,
  getEditFieldConfig,
} from "@/models/promotion";
import { useRouter, useRoute } from "vue-router";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";

/******* 頁面狀態與配置 *****************************/
const breadcrumbItems = [{ url: "", name: "推廣計劃" }];
const columns = tableColumns;
const filterConfig = filterFields;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// 分頁配置
const pagination = createPagination();

// 數據
const tableData = ref([]);
const editRecordId = ref<number>(0); // 當前編輯的推廣計劃ID
const editFormData = reactive<any>({}); // 當前編輯的推廣計劃數據

/******* 數據獲取與初始化 *****************************/
const fetchData = async (params?: any) => {
  loading.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await promotionApi.getPromotionList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取推廣計劃列表失敗", error);
  } finally {
    loading.value = false; // 結束加載
  }
};

watchRouteQuery(fetchData);

/******* 推廣計劃操作處理 *****************************/
// 搜索
const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 新建
const showModalCreate = ref(false);
const handleCreate = () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = getCreateFieldConfig();
  }
  showModalCreate.value = true;
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  try {
    const { validDate, ...rest } = data;
    const createData = {
      ...rest,
      validFrom: validDate[0],
      validTo: validDate[1],
    };
    await promotionApi.createPromotion(createData);
    message.success("創建推廣計劃成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchData(route.query);
  } catch (error) {
    console.error("創建推廣計劃失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 修改
const showModalEdit = ref(false);
const handleEdit = async (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  // 初始化編輯表單數據
  record.validDate = [record.validFrom, record.validTo];
  Object.assign(editFormData, record);
  showModalEdit.value = true;
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    const { validDate, ...rest } = data;
    const editData = {
      ...rest,
      validFrom: validDate[0],
      validTo: validDate[1],
    };
    await promotionApi.updatePromotion(editRecordId.value, editData);
    message.success("修改推廣計劃成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改推廣計劃失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

// 查看
const handleView = (record: any) => {
  // console.log(record.id)
  // 跳轉到推廣計劃詳情頁面
  router.push({ name: "PromotionDetail", params: { id: record.id } });
};

// 刪除
const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除推廣計劃 ${record.title} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await promotionApi.deletePromotion(record.id);
        message.success("刪除推廣計劃成功");
        fetchData();
      } catch (error) {
        console.error("刪除推廣計劃失敗:", error);
      }
    },
  });
};
</script>

<style scoped></style>
